/**
 * Copyright (c) 2024 - CARThunder
 * All Rights Reserved by Chengdu CARThunder Intelligent Technology Co., LTD and its affiliates.
 * You may not use, copy, distribute, modify, transmit in any form this file
 * except in compliance with CARThunder in writing by applicable law.
 * <p>
 * <p>
 * file description.
 *
 * @file filename
 * @brief brief function description.
 * @details detailed function description.
 * @version 1.0
 * @author author_name
 * @date last_modified_date
 * <p>
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2024-07-30              junjieluo         Create it.
 * <p>
 * file description.
 * @file filename
 * @brief brief function description.
 * @details detailed function description.
 * @version 1.0
 * @author author_name
 * @date last_modified_date
 * <p>
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2024-07-30              junjieluo         Create it.
 */

/**
 * file description.
 * @file filename
 * @brief brief function description.
 * @details detailed function description.
 * @version 1.0
 * @author author_name
 * @date last_modified_date
 *
 *      Edit History
 *      ----------------------------------------------------------------------------
 *      DATE                     NAME               DESCRIPTION
 *      2024-07-30              junjieluo         Create it.
 *
 */

package com.cart.musicdemo.base.service;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.SeekBar;
import com.cart.musicdemo.MainActivity;
import com.cart.musicdemo.base.utils.PreferencesUtil;

import java.lang.ref.WeakReference;

/**
 * The type Progress bar handler.
 */
public class ProgressBarHandler extends Handler implements SeekBar.OnSeekBarChangeListener {

    private static final String TAG = ProgressBarHandler.class.getSimpleName();

    private static final int MESSAGE = 0x01;

    private static final long MESSAGE_TIME = 1000L;

    private WeakReference<MusicPlayerManager> serviceReference;

    private final SeekBar seekBar;


    private Context context;

    /**
     * Instantiates a new Progress bar handler.
     *
     * @param seekBar the seek bar
     */
    public ProgressBarHandler(Context context, SeekBar seekBar) {
        super(Looper.getMainLooper());
        this.context = context;
        this.seekBar = seekBar;
        this.seekBar.setOnSeekBarChangeListener(this);
    }

    /**
     * Sets music player service.
     *
     * @param service the service
     */
    public void setMusicPlayerService(MusicPlayerManager service) {
        this.serviceReference = new WeakReference<>(service);
    }

    // 更新进度条方法
    public void updateProgress() {
        int pos = 0;
        int position = PreferencesUtil.getPlaybackPosition(context);
        int duration = PreferencesUtil.getPlayBackDuration(context);
        if (duration > 0) {
            pos = (int) (seekBar.getMax() * position / (duration * 1.0f));
        }
        seekBar.setProgress(pos);
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (msg.what == MESSAGE) {
            int pos = 0;

            // 获取 MusicPlayerManager 的实例
            MusicPlayerManager service = serviceReference.get();

            // 检查服务是否存在并且音乐正在播放，且 seekBar 未被按下
            if (service != null && service.isPlaying() && !seekBar.isPressed()) {
                // 获取当前播放位置和总时长（毫秒）
                int position = service.getMediaPlayer().getCurrentPosition();
                int duration = service.getMediaPlayer().getDuration();

                // 计算 SeekBar 应该设置的位置
                if (duration > 0) {
                    pos = (int) (seekBar.getMax() * position / (duration * 1.0f));
                }

                // 更新显示的文本信息，例如当前播放位置和总时长
                service.getText().setText(service.getCurrentPlayingInfo(position, duration));

                // 保存当前播放位置到 SharedPreferences
                PreferencesUtil.savePlaybackPosition(context, position);
                PreferencesUtil.savePlayBackDuration(context, duration);
            }

            // 设置 SeekBar 的进度
            seekBar.setProgress(pos);

            // 延迟发送下一条 MESSAGE 消息，用于定时更新进度
            sendEmptyMessageDelayed(MESSAGE, MESSAGE_TIME);
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            // 获取 MusicPlayerManager 的实例
            MusicPlayerManager musicPlayerHelper = serviceReference.get();
            if (musicPlayerHelper != null) {
                // 获取当前音乐的总时长（毫秒）
                int musicMax = musicPlayerHelper.getMediaPlayer().getDuration();

                // 获取 SeekBar 的最大值
                int seekBarMax = seekBar.getMax();

                // 计算要跳转到的具体时间点（毫秒）
                float msec = progress / (seekBarMax * 1.0F) * musicMax;

                // 将 MediaPlayer 跳转到计算出的时间点
                musicPlayerHelper.getMediaPlayer().seekTo((int) msec);

                // 更新显示的文本信息，例如当前播放位置和总时长
                int position = musicPlayerHelper.getMediaPlayer().getCurrentPosition();
                int duration = musicPlayerHelper.getMediaPlayer().getDuration();
                musicPlayerHelper.getText().setText(musicPlayerHelper
                        .getCurrentPlayingInfo(position, duration));

                // 保存当前播放位置到 SharedPreferences
                PreferencesUtil.savePlaybackPosition(context, position);
                PreferencesUtil.savePlayBackDuration(context, duration);
            }
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        removeMessages(MESSAGE);
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        MusicPlayerManager musicPlayerHelper = serviceReference.get();
        if (musicPlayerHelper != null) {
            int progress = seekBar.getProgress();
            Log.i(TAG, "onStopTrackingTouch " + progress);

            // 获取当前播放音乐的总时长 (milliseconds)
            int musicMax = musicPlayerHelper.getMediaPlayer().getDuration();

            // 获取 SeekBar 最大值
            int seekBarMax = seekBar.getMax();

            // 计算应跳转到的具体时间点
            float msec = progress / (seekBarMax * 1.0F) * musicMax;

            // 将 MediaPlayer 跳转到计算出的时间点
            musicPlayerHelper.getMediaPlayer().seekTo((int) msec);

            // 检查歌曲是否为暂停状态，如果是，则调用 Activity 的开始按钮
            Context context = seekBar.getContext();
            if (context instanceof MainActivity) {
                MainActivity mainActivity = (MainActivity) context;
                if (!musicPlayerHelper.isPlaying()) {
                    mainActivity.triggerStartButton();
                }
            }

            sendEmptyMessageDelayed(MESSAGE, MESSAGE_TIME);
        }
    }

    /**
     * Sets secondary progress.
     *
     * @param percent the percent
     */
    public void setSecondaryProgress(int percent) {
        seekBar.setSecondaryProgress(percent);
    }

    /**
     * Sets progress.
     *
     * @param progress the progress
     */
    public void setProgress(int progress) {
        seekBar.setProgress(progress);
    }

    /**
     * Gets max.
     *
     * @return the max
     */
    public int getMax() {
        return seekBar.getMax();
    }

    /**
     * Is seek bar pressed boolean.
     *
     * @return the boolean
     */
    public boolean isSeekBarPressed() {
        return seekBar.isPressed();
    }
}